package com.ywb.edugui.utils;



import java.awt.Color;

import java.awt.Image;

import java.awt.image.BufferedImage;

import java.awt.Graphics2D;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

/**
 *  ImageUtils图片工具类
 *  zoom:根据自定的大小缩放图片 (String | Image)
 *  @author 10147
 * @return BufferedImage
 *  bufferedImageToInputStream(BufferedImage ):将BufferedImage转化为输入流
 *  urlToImageIcon(String):读取str中的url地址转化为ImageIcon
 *
 */
public class ImageUtils {
    //缩略图宽度
    private static final int WIDTH = 100;
    //缩略图高度
    private static final int HEIGHT = 100;

    public static BufferedImage zoom(String srcFileName) {
        Image srcImage = new ImageIcon(srcFileName).getImage();
        //构造一个预定义的图像类型的BufferedImage对象。
        BufferedImage buffImg = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
        buffImg.flush();
        //创建Graphics2D对象，用于在BufferedImage对象上绘图。
        Graphics2D g = buffImg.createGraphics();
        //设置图形上下文的当前颜色为白色。
        g.setColor(Color.WHITE);
        //用图形上下文的当前颜色填充指定的矩形区域。
        g.fillRect(0, 0, WIDTH, HEIGHT);
        //按照缩放的大小在BufferedImage对象上绘制原始图像。
        g.drawImage(srcImage, 0, 0, WIDTH, HEIGHT, null);
        g.dispose();
        srcImage.flush();
        return buffImg;

    }
    public static InputStream bufferedImageToInputStream(BufferedImage img){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try{
//            将Image输出到字节数组流中
            ImageIO.write(img, "png",  os);
//            将字节数组流转为字节数组然后作为参数传入ByteArrayInputStream中
            return new ByteArrayInputStream(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static ImageIcon urlToImageIcon(String strUrl){
        try{
            URL url = new URL(strUrl);
            BufferedInputStream bis = new BufferedInputStream(url.openStream());
            BufferedImage bufferedImage = ImageIO.read(url);
            return new ImageIcon(bufferedImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
